<!-- eslint-disable vue/no-deprecated-v-on-native-modifier -->
<template>
    <div>
        <el-input v-model="keyword" placeholder="请输入关键字"></el-input>

        <el-table ref="table" :data="tableData" style="width: 100%" @scroll.native="handleScroll(keyword)">
            <el-table-column prop="date" label="日期" width="180"></el-table-column>
            <el-table-column prop="name" label="姓名" width="180">
                <template #default="{ row }">
                    <div :style="{ border: row.highlight ? '1px solid #ee0b0b' : '' }">{{ row.name }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="address" label="地址">
                <template #default="{ row }">
                    <div :style="{ border: row.highlight ? '1px solid #ee0b0b' : '' }">{{ row.address }}</div>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>
<script>
export default {
    data() {
        return {
            tableData: [
                { date: '2022-01-01', name: '张三', address: '北京市朝阳区', highlight: false },
                { date: '2022-01-02', name: '李四', address: '上海市浦东新区', highlight: false },
                { date: '2022-01-03', name: '王五', address: '广州市天河区', highlight: false }
            ],
            keyword: ''
        };
    },
    methods: {
        handleScroll(keyword) {
            const table = this.$refs.table.$el;
            const scrollTop = table.scrollTop;
            // const cells = table.querySelectorAll('.el-table__body-wrapper td');

            // 遍历所有单元格，找到匹配的单元格
            let targetCell = null;
            for (let i = 0; i < this.tableData.length; i++) {
                const row = this.tableData[i];
                if (row.name.includes(keyword)) {
                    row.highlight = true;
                    targetCell = this.$refs.table.$el.querySelector(`.el-table__body-wrapper tr:nth-child(${i + 1}) td:nth-child(2)`);
                    break;
                } else if (row.address.includes(keyword)) {
                    row.highlight = true;
                    targetCell = this.$refs.table.$el.querySelector(`.el-table__body-wrapper tr:nth-child(${i + 1}) td:nth-child(3)`);
                    break;
                }
            }

            // 如果找到了匹配的单元格，平滑滚动到单元格位置
            if (targetCell) {
                const rect = targetCell.getBoundingClientRect();
                table.scrollTo({
                    top: scrollTop + rect.top - 50, // 50为表头高度
                    behavior: 'smooth'
                });
            }
        }
    }
};
</script>